// ============================================================================
// 编辑关键字窗口模态框组件
// ============================================================================

import React, { useState, useEffect } from 'react'
import { keywordWindowService, KeywordWindowDetails, KeywordWindowUpdateParams } from '../services/keyword-window-service'
import { useNotifications } from '../hooks/use-notifications'
import { logger } from '../utils/logger'

interface EditKeywordWindowModalProps {
  window: KeywordWindowDetails
  onClose: () => void
  onSuccess: () => void
}

/**
 * 编辑关键字窗口模态框组件
 */
export const EditKeywordWindowModal: React.FC<EditKeywordWindowModalProps> = ({
  window,
  onClose,
  onSuccess
}) => {
  const [loading, setLoading] = useState(false)
  const [hasMoreHistory, setHasMoreHistory] = useState(window.details.hasMoreHistory)
  const [startTime, setStartTime] = useState(
    window.details.startTime ? formatDateTimeLocal(window.details.startTime) : ''
  )
  const [endTime, setEndTime] = useState(
    window.details.endTime ? formatDateTimeLocal(window.details.endTime) : ''
  )
  const [timeRanges, setTimeRanges] = useState<any>(null)
  const { showSuccess, showError } = useNotifications()

  // 加载时间范围信息
  useEffect(() => {
    loadTimeRanges()
  }, [window.keyword])

  /**
   * 格式化日期时间为本地输入格式
   */
  function formatDateTimeLocal(date: Date | string): string {
    const d = typeof date === 'string' ? new Date(date) : date
    if (isNaN(d.getTime())) return ''
    
    // 格式化为 YYYY-MM-DDTHH:mm (本地时间)
    const year = d.getFullYear()
    const month = String(d.getMonth() + 1).padStart(2, '0')
    const day = String(d.getDate()).padStart(2, '0')
    const hours = String(d.getHours()).padStart(2, '0')
    const minutes = String(d.getMinutes()).padStart(2, '0')
    
    return `${year}-${month}-${day}T${hours}:${minutes}`
  }

  /**
   * 解析本地日期时间输入
   */
  function parseLocalDateTime(dateTimeLocal: string): Date | null {
    if (!dateTimeLocal) return null
    return new Date(dateTimeLocal)
  }

  /**
   * 加载时间范围信息
   */
  const loadTimeRanges = async () => {
    try {
      const ranges = await keywordWindowService.getKeywordTimeRanges(window.keyword)
      setTimeRanges(ranges)
    } catch (error) {
      logger.error('加载时间范围信息失败', error)
    }
  }

  /**
   * 提交表单
   */
  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault()
    
    if (loading) return

    try {
      setLoading(true)

      const updates: KeywordWindowUpdateParams = {
        hasMoreHistory
      }

      // 只在用户修改了时间时才更新
      const newStartTime = parseLocalDateTime(startTime)
      const newEndTime = parseLocalDateTime(endTime)

      if (newStartTime && (!window.details.startTime || 
          newStartTime.getTime() !== new Date(window.details.startTime).getTime())) {
        updates.startTime = newStartTime
      }

      if (newEndTime && (!window.details.endTime || 
          newEndTime.getTime() !== new Date(window.details.endTime).getTime())) {
        updates.endTime = newEndTime
      }

      // 验证时间范围
      if (newStartTime && newEndTime && newStartTime >= newEndTime) {
        showError('时间范围错误', '开始时间必须早于结束时间')
        return
      }

      await keywordWindowService.updateKeywordWindow(window.keyword, updates)
      
      showSuccess('窗口设置已更新', `关键字"${window.keyword}"的窗口设置已更新`)
      onSuccess()
    } catch (error) {
      logger.error('更新窗口设置失败', error)
      showError('更新失败', `${(error as Error).message}`)
    } finally {
      setLoading(false)
    }
  }

  /**
   * 重置窗口
   */
  const handleReset = async () => {
    if (!confirm(`确定要重置关键字"${window.keyword}"的窗口设置吗？这将清除时间范围和统计信息。`)) {
      return
    }

    try {
      setLoading(true)
      await keywordWindowService.resetKeywordWindow(window.keyword)
      showSuccess('窗口已重置', `关键字"${window.keyword}"的窗口设置已重置`)
      onSuccess()
    } catch (error) {
      logger.error('重置窗口失败', error)
      showError('重置失败', `${(error as Error).message}`)
    } finally {
      setLoading(false)
    }
  }

  return (
    <div className="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50">
      <div className="bg-white rounded-lg shadow-xl w-full max-w-2xl mx-4 max-h-[90vh] overflow-y-auto">
        {/* 模态框标题 */}
        <div className="px-6 py-4 border-b">
          <div className="flex items-center justify-between">
            <h2 className="text-xl font-semibold text-gray-900">
              编辑关键字窗口设置
            </h2>
            <button
              onClick={onClose}
              className="text-gray-400 hover:text-gray-600"
            >
              <svg className="w-6 h-6" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M6 18L18 6M6 6l12 12" />
              </svg>
            </button>
          </div>
          <p className="text-sm text-gray-600 mt-1">
            关键字: <span className="font-medium">{window.keyword}</span>
          </p>
        </div>

        {/* 当前状态信息 */}
        <div className="px-6 py-4 bg-gray-50">
          <h3 className="text-sm font-medium text-gray-900 mb-3">当前状态</h3>
          <div className="grid grid-cols-2 gap-4 text-sm">
            <div>
              <span className="text-gray-600">总帖子数:</span>
              <span className="ml-2 font-medium">{window.details.totalPostsCrawled.toLocaleString()}</span>
            </div>
            <div>
              <span className="text-gray-600">最新帖子:</span>
              <span className="ml-2 font-medium">{window.details.latestPostsCrawled.toLocaleString()}</span>
            </div>
            <div>
              <span className="text-gray-600">历史帖子:</span>
              <span className="ml-2 font-medium">{window.details.historyPostsCrawled.toLocaleString()}</span>
            </div>
            <div>
              <span className="text-gray-600">最后历史爬取:</span>
              <span className="ml-2 font-medium">
                {keywordWindowService.formatDateTime(window.details.lastHistoryCrawlAt)}
              </span>
            </div>
          </div>
        </div>

        {/* 时间范围信息 */}
        {timeRanges && (
          <div className="px-6 py-4 bg-blue-50">
            <h3 className="text-sm font-medium text-blue-900 mb-3">下次搜索时间范围</h3>
            <div className="space-y-2 text-sm">
              {timeRanges.latestRange && (
                <div>
                  <span className="text-blue-700">最新搜索:</span>
                  <span className="ml-2 font-mono text-xs bg-blue-100 px-2 py-1 rounded">
                    {timeRanges.latestRange.startTime} - {timeRanges.latestRange.endTime}
                  </span>
                </div>
              )}
              {timeRanges.historyRange && timeRanges.shouldCrawlHistory && (
                <div>
                  <span className="text-blue-700">历史搜索:</span>
                  <span className="ml-2 font-mono text-xs bg-blue-100 px-2 py-1 rounded">
                    {timeRanges.historyRange.startTime || '起始'} - {timeRanges.historyRange.endTime}
                  </span>
                </div>
              )}
              {!timeRanges.shouldCrawlHistory && (
                <div className="text-blue-700">历史搜索: 暂不需要</div>
              )}
            </div>
          </div>
        )}

        {/* 编辑表单 */}
        <form onSubmit={handleSubmit} className="px-6 py-4 space-y-4">
          {/* 历史爬取状态 */}
          <div>
            <label className="block text-sm font-medium text-gray-700 mb-2">
              历史爬取状态
            </label>
            <div className="flex items-center space-x-4">
              <label className="flex items-center">
                <input
                  type="radio"
                  checked={hasMoreHistory}
                  onChange={() => setHasMoreHistory(true)}
                  className="w-4 h-4 text-blue-600 border-gray-300 focus:ring-blue-500"
                />
                <span className="ml-2 text-sm text-gray-700">有更多历史数据需要爬取</span>
              </label>
              <label className="flex items-center">
                <input
                  type="radio"
                  checked={!hasMoreHistory}
                  onChange={() => setHasMoreHistory(false)}
                  className="w-4 h-4 text-blue-600 border-gray-300 focus:ring-blue-500"
                />
                <span className="ml-2 text-sm text-gray-700">历史数据已完成</span>
              </label>
            </div>
            <p className="text-xs text-gray-500 mt-1">
              设置为"已完成"将停止该关键字的历史爬取
            </p>
          </div>

          {/* 开始时间 */}
          <div>
            <label htmlFor="startTime" className="block text-sm font-medium text-gray-700 mb-2">
              窗口开始时间 (可选)
            </label>
            <input
              type="datetime-local"
              id="startTime"
              value={startTime}
              onChange={(e) => setStartTime(e.target.value)}
              className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-transparent"
            />
            <p className="text-xs text-gray-500 mt-1">
              设置爬取时间窗口的开始边界
            </p>
          </div>

          {/* 结束时间 */}
          <div>
            <label htmlFor="endTime" className="block text-sm font-medium text-gray-700 mb-2">
              窗口结束时间 (可选)
            </label>
            <input
              type="datetime-local"
              id="endTime"
              value={endTime}
              onChange={(e) => setEndTime(e.target.value)}
              className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-transparent"
            />
            <p className="text-xs text-gray-500 mt-1">
              设置爬取时间窗口的结束边界
            </p>
          </div>

          {/* 警告信息 */}
          <div className="bg-yellow-50 border border-yellow-200 rounded-lg p-3">
            <div className="flex items-start space-x-2">
              <svg className="w-5 h-5 text-yellow-600 flex-shrink-0 mt-0.5" fill="currentColor" viewBox="0 0 20 20">
                <path fillRule="evenodd" d="M8.257 3.099c.765-1.36 2.722-1.36 3.486 0l5.58 9.92c.75 1.334-.213 2.98-1.742 2.98H4.42c-1.53 0-2.493-1.646-1.743-2.98l5.58-9.92zM11 13a1 1 0 11-2 0 1 1 0 012 0zm-1-8a1 1 0 00-1 1v3a1 1 0 002 0V6a1 1 0 00-1-1z" clipRule="evenodd" />
              </svg>
              <div>
                <h4 className="text-sm font-medium text-yellow-800">注意事项</h4>
                <div className="text-xs text-yellow-700 mt-1">
                  <p>• 修改时间范围将影响下次爬取的搜索范围</p>
                  <p>• 通常情况下，系统会自动维护时间窗口，无需手动调整</p>
                  <p>• 只有在需要特殊调整时才手动修改时间范围</p>
                </div>
              </div>
            </div>
          </div>

          {/* 按钮组 */}
          <div className="flex items-center justify-between pt-4">
            <button
              type="button"
              onClick={handleReset}
              disabled={loading}
              className="px-4 py-2 bg-yellow-100 text-yellow-700 rounded-lg hover:bg-yellow-200 disabled:opacity-50 text-sm font-medium"
            >
              重置窗口
            </button>

            <div className="flex items-center space-x-3">
              <button
                type="button"
                onClick={onClose}
                disabled={loading}
                className="px-4 py-2 bg-gray-100 text-gray-700 rounded-lg hover:bg-gray-200 disabled:opacity-50 text-sm font-medium"
              >
                取消
              </button>
              <button
                type="submit"
                disabled={loading}
                className="px-4 py-2 bg-blue-600 text-white rounded-lg hover:bg-blue-700 disabled:opacity-50 text-sm font-medium"
              >
                {loading ? '保存中...' : '保存设置'}
              </button>
            </div>
          </div>
        </form>
      </div>
    </div>
  )
}
